// 全局变量
let elevatorData = [];
let requestCountByFloor = Array(4).fill(0); // 索引0不用，1-10对应楼层
let elevatorUsageCount = [0, 0]; // 索引0不用，1-3对应电梯

// 初始化图表
let usageChart, floorRequestChart;

function initCharts() {
    // 电梯使用频率图表
    const usageCtx = document.getElementById('usage-chart').getContext('2d');
    usageChart = new Chart(usageCtx, {
        type: 'bar',
        data: {
            labels: ['电梯 #1'],
            datasets: [{
                label: '使用次数',
                data: [0, 0, 0],
                backgroundColor: [
                    'rgba(59, 130, 246, 0.7)',
                    'rgba(16, 185, 129, 0.7)',
                    'rgba(245, 158, 11, 0.7)'
                ],
                borderColor: [
                    'rgba(59, 130, 246, 1)',
                    'rgba(16, 185, 129, 1)',
                    'rgba(245, 158, 11, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        precision: 0
                    }
                }
            }
        }
    });

    // 楼层请求分布图表
    const floorCtx = document.getElementById('floor-request-chart').getContext('2d');
    floorRequestChart = new Chart(floorCtx, {
        type: 'pie',
        data: {
            labels: ['1楼', '2楼', '3楼'],
            datasets: [{
                label: '请求次数',
                data: requestCountByFloor.slice(1),
                backgroundColor: [
                    'rgba(59, 130, 246, 0.7)',
                    'rgba(16, 185, 129, 0.7)',
                    'rgba(245, 158, 11, 0.7)',
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true
        }
    });
}

// 请求电梯
function requestElevator(floor, direction) {
    fetch('/api/request', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ floor: floor, direction: direction })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新请求计数
            requestCountByFloor[floor]++;
            updateCharts();

            // 视觉反馈
            const btnClass = direction === 'up' ? 'fa-arrow-up' : 'fa-arrow-down';
//            document.querySelector(`.request-btn:has(.${btnClass})`).classList.add('bg-primary', 'text-white');
            setTimeout(() => {
                document.querySelector(`.request-btn:has(.${btnClass})`).classList.remove('bg-primary', 'text-white');
            }, 1000);
        }
    });
}

// 为指定电梯设置目标楼层
function setElevatorTarget(elevatorId) {
    const selectElement = document.getElementById(`elevator-${elevatorId}-target-select`);
    const floor = selectElement.value;

    fetch(`/api/elevator/${elevatorId}/target`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ floor: floor })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新使用计数
            elevatorUsageCount[elevatorId]++;
            updateCharts();

            // 视觉反馈
            const btn = document.querySelector(`button[onclick="setElevatorTarget(${elevatorId})"]`);
            btn.classList.add('bg-green-600');
            setTimeout(() => {
                btn.classList.remove('bg-green-600');
            }, 1000);
        }
    });
}

// 更新图表数据
function updateCharts() {
    usageChart.data.datasets[0].data = elevatorUsageCount.slice(1);
    usageChart.update();

    floorRequestChart.data.datasets[0].data = requestCountByFloor.slice(1);
    floorRequestChart.update();
}

// 更新电梯显示
function updateElevatorDisplay() {
    fetch('/api/status')
        .then(response => response.json())
        .then(data => {
            elevatorData = data;

            // 更新概览统计
            let activeCount = 0;
            let idleCount = 0;

            data.forEach(elevator => {
                // 更新电梯位置
                const position = (elevator.current_floor - 1) * 60; // 每层40px
                const elevatorElement = document.getElementById(`elevator-${elevator.id}`);
                elevatorElement.style.bottom = `${position}px`;
                elevatorElement.textContent = elevator.current_floor;

                // 更新电梯状态文本
                const statusElement = document.getElementById(`elevator-${elevator.id}-status`);
                statusElement.textContent = `状态: ${elevator.status}`;

                // 更新详细信息
                document.getElementById(`elevator-${elevator.id}-floor`).textContent = elevator.current_floor;
                document.getElementById(`elevator-${elevator.id}-status-detailed`).textContent = elevator.status;
                document.getElementById(`elevator-${elevator.id}-direction`).textContent = elevator.direction || '无';
                document.getElementById(`elevator-${elevator.id}-passengers`).textContent = elevator.passengers;
                document.getElementById(`elevator-${elevator.id}-targets`).textContent = elevator.target_floors.length > 0 ? elevator.target_floors.join(', ') : '无';
                document.getElementById(`elevator-${elevator.id}-activity`).textContent = elevator.last_activity;

                // 更新状态颜色
                let colorClass = 'bg-primary'; // 默认蓝色
                if (elevator.status === '向上运行') {
                    colorClass = 'bg-secondary'; // 绿色
                    activeCount++;
                } else if (elevator.status === '向下运行') {
                    colorClass = 'bg-warning'; // 黄色
                    activeCount++;
                } else if (elevator.status === '门打开') {
                    colorClass = 'bg-purple-500'; // 紫色
                } else if (elevator.status === '空闲') {
                    idleCount++;
                }

                // 移除所有颜色类并添加当前状态的颜色类
                elevatorElement.className = 'elevator-car';
                elevatorElement.classList.add(...colorClass.split(' '));
            });

            // 更新概览数据
            document.getElementById('active-elevators').textContent = activeCount;
            document.getElementById('idle-elevators').textContent = idleCount;
            // 简单估算等待请求数
            const pendingRequests = data.reduce((sum, elevator) => sum + elevator.target_floors.length, 0);
            document.getElementById('pending-requests').textContent = pendingRequests;
        })
        .catch(error => console.error('Error fetching elevator status:', error));
}

// 页面加载完成后初始化
window.onload = function() {
    initCharts();
    updateElevatorDisplay();

    // 每2秒更新一次电梯状态
    setInterval(updateElevatorDisplay, 500);
};